package com.common.es.service;

import com.common.es.instance.EsInstance;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.stereotype.Service;

import java.io.IOException;

import static com.common.es.config.EsConstant.DEFAULT_OPTIONS;

/**
 * @author 牧鱼
 * @Classname EsService
 * @Description TODO
 * @Date 2021/5/10
 */
@Service
public class EsService {

    private RestHighLevelClient restClient = null;

    /**
     * 在ES实例当中获取ES连接对象
     * @param esInstance
     */
    public EsService(EsInstance esInstance) {
        restClient = esInstance.getRestClient();
    }


    /**
     * 通过索引和ID删除
     * @param index
     * @param id
     */
    public DeleteResponse delete(String index,String id){
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.index(index);
        deleteRequest.id(id);
        DeleteResponse response = null;
        try {
            response = restClient.delete(deleteRequest,DEFAULT_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 通过单个条件删除记录
     * @param index
     * @param fieldName
     * @param value
     * @throws IOException
     */
    private BulkByScrollResponse testSingleDelQuery(String index,String fieldName , String value) {
        DeleteByQueryRequest request=new DeleteByQueryRequest();
        request.indices(index);
        request.setQuery(new MatchQueryBuilder(fieldName,value));
        BulkByScrollResponse response = null;
        //分词式删除
        try {
            response = restClient.deleteByQuery(request, DEFAULT_OPTIONS);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return response;
    }


}
